package com.xiaojiezhu.test.mybatis;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.Test;
import org.mybatis.spring.SqlSessionFactoryBean;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * 作者 zxj<br>
 * 时间 2017/10/22 17:00
 * 说明 ...
 */
public class MybadisJavaCode {
    @Test
    public void test(){
        SqlSessionFactory sqlSessionFactory = createSqlSessionFactory();
        SqlSession session = sqlSessionFactory.openSession();
        OrgDao mapper = session.getMapper(OrgDao.class);
        List<Map<String, Object>> maps = mapper.queryAll();
        System.out.println(maps);
    }

    private SqlSessionFactory createSqlSessionFactory(){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        DataSource dataSource = createDataSource();
        bean.setDataSource(dataSource);


        bean.setPlugins(new Interceptor[]{new MyPlugin()});

        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(OrgDao.class);
        bean.setConfiguration(configuration);

        try {
            SqlSessionFactory object = bean.getObject();
            return object;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private DataSource createDataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setUsername("root");
        ds.setPassword("MYsql@123#ll");
        ds.setUrl("jdbc:mysql://10.8.16.231:3306/testsaas?useUnicode=true&characterEncoding=utf8");
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        return ds;
    }
}
